import router from '@/router'
import store from '@/store' // 引入store实例 和组件中的this.$store是一回事
import nprogress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

nprogress.configure({ showSpinner: false }) // nprogress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  nprogress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已登录
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，请重定向到主页
      next('/')
    } else {
      if (!store.getters.userId) {
        await store.dispatch('user/getUserInfo')
        console.log('进入这里')
        // next()
        // } else {
        const menuList = await store.dispatch('user/getMenuList')
        console.log('getMenuList-roles: ', menuList)
        let roles = []
        function getRolesList(list) {
          list.forEach(item => {
            roles.push(item.permissionId)
            if (item.children) {
              getRolesList(item.children)
            }
          })
        }
        getRolesList(menuList)
        console.log('roles', roles)
        // 获得用户信息
        const routes = await store.dispatch('permission/filterRoutes', roles)
        console.log(routes)
        router.addRoutes([
          ...routes,
          { path: '*', redirect: '/404', hidden: true }
        ])
        // 添加到路由
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    //   没有token的情况下
    if (whiteList.indexOf(to.path) > -1) {
      //  表示要去的地址在白名单
      next()
    } else {
      next('/login')
    }
  }
  nprogress.done() // 解决手动切换地址时 进度条不关闭的问题
})
// 后置守卫
router.afterEach(() => {
  nprogress.done() // 关闭进度条
})
